#!/usr/bin/env python3
"""
调试脚本：详细诊断absorption错误
"""

import sys
import os
import traceback

# 添加模块路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

try:
    from src.absorption.absorption_module import AbsorptionModel
    from src.distribution.distribution_module import DistributionModel
    from src.elimination.elimination_module import EliminationModel
    from src.population.population_data import PopulationData
    from src.utils.config_manager import ConfigManager
    
    print("=== 开始调试PBPK系统 ===")
    
    # 加载配置
    config = ConfigManager('../config/example.json')
    params = config.get_model_params()
    print(f"✓ 配置加载成功，参数键: {list(params.keys())}")
    
    # 检查参数
    print(f"药物名称: {params.get('name', 'N/A')}")
    print(f"剂量: {params.get('dose', 'N/A')}")
    print(f"ka: {params.get('ka', 'N/A')}")
    print(f"Vp: {params.get('Vp', 'N/A')}")
    print(f"CL_hepatic: {params.get('CL_hepatic', 'N/A')}")
    
    # 创建人群数据
    pop_data = PopulationData()
    default_pop = pop_data.get_default_population()
    individual_params = default_pop['individual_001']
    print(f"✓ 人群数据加载成功，个体参数键: {list(individual_params.keys())[:10]}...")
    
    # 创建时间序列
    import numpy as np
    time_points = np.linspace(0, 24, 10)  # 少量时间点用于调试
    print(f"✓ 时间序列创建成功: {len(time_points)}个点")
    
    # 测试吸收模块
    print("\n--- 测试吸收模块 ---")
    abs_model = AbsorptionModel(params)
    print("✓ 吸收模型创建成功")
    
    abs_result = abs_model.calculate_absorption(individual_params, time_points)
    print(f"✓ 吸收计算完成，结果类型: {type(abs_result)}")
    print(f"  结果键: {list(abs_result.keys())}")
    
    # 测试分布模块
    print("\n--- 测试分布模块 ---")
    dist_model = DistributionModel(params)
    print("✓ 分布模型创建成功")
    
    dist_result = dist_model.calculate_distribution(individual_params, time_points, abs_result)
    print(f"✓ 分布计算完成，结果类型: {type(dist_result)}")
    print(f"  结果键: {list(dist_result.keys())}")
    
    # 测试消除模块
    print("\n--- 测试消除模块 ---")
    elim_model = EliminationModel(params)
    print("✓ 消除模型创建成功")
    
    elim_result = elim_model.calculate_elimination(individual_params, time_points, dist_result)
    print(f"✓ 消除计算完成，结果类型: {type(elim_result)}")
    print(f"  结果键: {list(elim_result.keys())}")
    
    print("\n🎉 所有模块测试通过！")
    
except Exception as e:
    print(f"❌ 调试失败: {e}")
    print("\n详细错误信息:")
    traceback.print_exc()
    
    # 尝试打印更多调试信息
    try:
        print(f"\n当前工作目录: {os.getcwd()}")
        print(f"文件路径: {__file__}")
        
        # 检查配置文件
        config_path = '../config/example.json'
        if os.path.exists(config_path):
            with open(config_path, 'r', encoding='utf-8') as f:
                content = f.read()[:200]
                print(f"配置文件内容预览: {content}")
    except:
        pass